<?php

class GenerateController extends Controller
{
	public function actionArticle()
	{
		$model = new GenerateForm();
		
		if(isset($_POST['ajax']) && $_POST['ajax']==='generate-form-article-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
		if(isset($_POST['GenerateForm']['wordCount'])) {
			$article = '';
			$word_count = 0;
			$model = new Words();
			$criteria = new CDbCriteria();
			while (true) {
				if(isset($words_id)) {
					$criteria->addNotInCondition('words_id', $words_id);
				}
				$model->setDbCriteria($criteria);
				$words = $model->find(array('order'=>'rand()'));
				if (!$words or $word_count>=$_POST['GenerateForm']['wordCount']){
					break;
				}
				$word_count += $words->word_count;
				$words_id[]=$words->words_id;
				$article .= $words->words.' ';
				if (rand(1, 5)==5) {
					$article .= "\n\n";
				} 
			}
			echo $article;
			Yii::app()->end();
		}
		$this->render('article',array(
			'model'=>$model,
		));
	}

	// Uncomment the following methods and override them if needed
	/*
	public function filters()
	{
		// return the filter configuration for this controller, e.g.:
		return array(
			'inlineFilterName',
			array(
				'class'=>'path.to.FilterClass',
				'propertyName'=>'propertyValue',
			),
		);
	}

	public function actions()
	{
		// return external action classes, e.g.:
		return array(
			'action1'=>'path.to.ActionClass',
			'action2'=>array(
				'class'=>'path.to.AnotherActionClass',
				'propertyName'=>'propertyValue',
			),
		);
	}
	*/
}